package edu.ynu.se.xiecheng.achitectureclass.service.impl;

import edu.ynu.se.xiecheng.achitectureclass.constant.YingShiConstants;
import edu.ynu.se.xiecheng.achitectureclass.dao.CameraCaptureRepository;
import edu.ynu.se.xiecheng.achitectureclass.entity.CameraCapture;
import edu.ynu.se.xiecheng.achitectureclass.exception.BusinessException;
import edu.ynu.se.xiecheng.achitectureclass.service.CameraService;
import edu.ynu.se.xiecheng.achitectureclass.service.OssService;
import edu.ynu.se.xiecheng.achitectureclass.service.YingShiTokenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class CameraServiceImpl implements CameraService {
    
    private final YingShiTokenService yingShiTokenService;
    private final RestTemplate restTemplate;
    private final CameraCaptureRepository cameraCaptureRepository;
    private final OssService ossService;
    
    private static final long MIN_CAPTURE_INTERVAL = 5000; // 最小拍照间隔（毫秒）
    private volatile Long lastCaptureTime = 0L;
    
    @Override
    public CameraCapture captureImage(Integer quality) {
        log.info("开始抓拍照片，设备序列号: {}, 质量: {}", YingShiConstants.DEVICE_SERIAL, quality);
        
        // 检查拍照间隔
        long currentTime = System.currentTimeMillis();
        synchronized (this) {
            if (currentTime - lastCaptureTime < MIN_CAPTURE_INTERVAL) {
                throw new BusinessException("请求过于频繁，请等待" + (MIN_CAPTURE_INTERVAL/1000) + "秒后再试");
            }
            lastCaptureTime = currentTime;
        }
        
        try {
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            
            // 构建表单数据
            MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
            formData.add("accessToken", yingShiTokenService.getAccessToken());
            formData.add("deviceSerial", YingShiConstants.DEVICE_SERIAL);
            formData.add("channelNo", String.valueOf(YingShiConstants.DEFAULT_CHANNEL_NO));
            if (quality != null) {
                formData.add("quality", String.valueOf(quality));
            }
            
            // 创建请求实体
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);
            
            // 发送请求
            ResponseEntity<Map> response = restTemplate.postForEntity(
                YingShiConstants.CAPTURE_URL,
                requestEntity,
                Map.class
            );
            
            if (response.getBody() != null && "200".equals(response.getBody().get("code"))) {
                // 获取萤石云的图片URL
                Map<String, String> data = (Map<String, String>) response.getBody().get("data");
                String yingshiUrl = data.get("picUrl");
                
                // 上传到阿里云OSS
                String ossUrl = ossService.uploadImage(yingshiUrl, "camera_captures");
                
                // 保存抓拍记录到数据库
                CameraCapture capture = new CameraCapture();
                capture.setDeviceSerial(YingShiConstants.DEVICE_SERIAL);
                capture.setPicUrl(ossUrl);
                capture.setQuality(quality != null ? quality : YingShiConstants.DEFAULT_QUALITY);
                return cameraCaptureRepository.save(capture);
            }
            
            throw new BusinessException(response.getBody() != null ? 
                response.getBody().get("msg").toString() : "抓拍失败，请稍后重试");
        } catch (Exception e) {
            log.error("抓拍照片失败", e);
            throw new BusinessException("抓拍失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public List<CameraCapture> getCapturesByTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        log.info("获取时间范围内的抓拍记录，开始时间: {}, 结束时间: {}", startTime, endTime);
        return cameraCaptureRepository.findByCaptureTimeBetweenOrderByCaptureTimeDesc(startTime, endTime);
    }
    
    @Override
    public List<CameraCapture> getLastWeekCaptures() {
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = endTime.minusWeeks(1);
        log.info("获取最近一周的抓拍记录，开始时间: {}, 结束时间: {}", startTime, endTime);
        return getCapturesByTimeRange(startTime, endTime);
    }
    
    @Override
    public Map<String, String> getCameraInfo() {
        log.info("获取摄像头信息");
        Map<String, String> info = new HashMap<>();
        info.put("deviceSerial", YingShiConstants.DEVICE_SERIAL);
        info.put("liveAddress", YingShiConstants.LIVE_ADDRESS);
        info.put("accessToken", yingShiTokenService.getAccessToken());
        return info;
    }
    
    @Override
    public Map<String, Object> getCameraToken() {
        log.info("获取摄像头访问令牌");
        try {
            String token = yingShiTokenService.getAccessToken();
            
            Map<String, Object> tokenInfo = new HashMap<>();
            tokenInfo.put("accessToken", token);
            tokenInfo.put("expireTime", LocalDateTime.now().plusHours(2));  // token有效期2小时
            return tokenInfo;
        } catch (Exception e) {
            log.error("获取摄像头访问令牌失败", e);
            throw new BusinessException("获取摄像头访问令牌失败: " + e.getMessage(), e);
        }
    }
} 